package com.xiaoka.ins.corp.api.gpic.service.impl;

import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.List;

import javax.xml.bind.JAXBException;
import javax.xml.transform.stream.StreamResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.stereotype.Service;

import com.xiaoka.freework.utils.Utils;
import com.xiaoka.freework.utils.http.HttpExecutor;
import com.xiaoka.ins.corp.api.config.GpicConfig;
import com.xiaoka.ins.corp.api.dto.request.PremiumCalculationParam;
import com.xiaoka.ins.corp.api.dto.request.RiskDto;
import com.xiaoka.ins.corp.api.dto.request.UnderwritingDto;
import com.xiaoka.ins.corp.api.gpic.dto.RootElementGPIC;
import com.xiaoka.ins.corp.api.gpic.help.DataConversion;
import com.xiaoka.ins.corp.api.gpic.help.GpicUtils;
import com.xiaoka.ins.corp.api.gpic.service.GpicInterface;
import com.xiaoka.ins.corp.api.gpic.service.GpicService;
import com.xiaoka.ins.corp.api.utils.BaseUtils;
import com.xiaoka.ins.corp.api.utils.JaxbUtils;

/**
 * @author azheng
 *
 */
@Service
public class GpicServiceImpl implements GpicService {

	private static final String STATUS_100 = "100"; // 成功(所有成功状态)
	private static final String STATUS_400 = "400"; // 失败（无法支付、无法出单等）
	public static final String STATUS_500 = "500"; // 核保中（出现400时保险公司一定要回调，无论成功还是失败）
	
	private final static Logger log = LoggerFactory.getLogger(GpicServiceImpl.class);
	
	@Autowired
	private GpicConfig gpicConfig;
	
	@Autowired
	private Jaxb2Marshaller jaxb2Marshaller;
	
	@Autowired
	private JaxbUtils jaxbUtils;
	
	@Autowired
	private GpicInterface gpicInterface;
	
	@Autowired
	private MongoTemplate mongoTemplate;
	
	public static final Charset Char_GBK = Charset.forName("GBK");
	
	/* (non-Javadoc)
	 * @see com.xiaoka.ins.corp.api.gpic.service.GpicService#getVehicleType(java.lang.String)
	 */
	@Override
	public String getVehicleType(String brandName) {
		String address = gpicConfig.getVehicleUrl() + brandName;
		String json = Utils.get(HttpExecutor.class).get(address).reqCharset(Char_GBK).executeAsString();
		json = BaseUtils.filterJson(json);
		return json;
	}
	
	/* (non-Javadoc)
	 * @see com.xiaoka.ins.corp.api.gpic.service.GpicService#getPremiumCalculation(com.xiaoka.ins.corp.api.dto.request.PremiumCalculationParam)
	 */
	@Override
	public String getPremiumCalculation(PremiumCalculationParam pc){
		pc.setId(pc.getId()!=null?pc.getId():"TE"+BaseUtils.getUniqueId());
		pc.getCustomerDto().setIdType("9");
		RootElementGPIC response = gpicInterface.doRequest100(pc);
		response = gpicInterface.doRequest105(response,pc);
		String status = response.get_package().getHeader().getStatus();
		if(STATUS_100.equals(status)){
			List<RiskDto> riskList = DataConversion.getRequestRiskList(
					pc.getRiskDtoList(),DataConversion.getRiskForm105Return(response));
			pc.setRiskDtoList(riskList);
			status = gpicInterface.doRequest110(pc,response.get_package().getHeader().getSessionId());
			pc = DataConversion.getPremiumCalculationPersistence(pc, response);
			mongoTemplate.save(pc);
		}else{
			StringWriter writer = new StringWriter();
			jaxb2Marshaller.marshal(response, new StreamResult(writer));
			status = GpicUtils.filterPackageListXml(writer.toString());
		}
		return status;
	}
	
	/* (non-Javadoc)
	 * @see com.xiaoka.ins.corp.api.gpic.service.GpicService#getUnderwriting(com.xiaoka.ins.corp.api.dto.request.UnderwritingDto)
	 */
	@Override
	public String getUnderwriting(UnderwritingDto check){
		PremiumCalculationParam cp = mongoTemplate.findById(check.getQuerySequenceNo(),PremiumCalculationParam.class);
		return cp!=null?gpicInterface.doRequest115(check,cp):null;
	}
	
	/* (non-Javadoc)
	 * @see com.xiaoka.ins.corp.api.gpic.service.GpicService#getPayUrl(java.lang.String)
	 */
	@Override
	public String getPayUrl(String seqNo) {
		RootElementGPIC response120 = gpicInterface.doRequest120(seqNo);
		String status = response120.get_package().getHeader().getStatus();
		if(STATUS_100.equals(status)){
			String payUrl = response120.get_package().getResponse().getOrder().getPaymentUrl();
			/*120接口返回支付地址,根据订单信息配置支付链接，保存支付链接*/
			/*String orderNo = response120.get_package().getResponse().getOrder().getOrderId();
			PayOrder payOrder = payOrderRepository.findBySeqNo(seqNo);
			payUrl = payUrl + "?sessionId=" + seqNo + "&sellerId=" + gpicConfig.getSellerId()+"&orderId="+orderNo+"&flagType=app&needType=no";
			payOrder.setOrderNO(orderNo);
			payOrder.setPayUrl(payUrl);
			payOrderRepository.save(payOrder);*/
			return payUrl;
		}else if(STATUS_400.equals(status)){
			log.error(response120.get_package().getHeader().getErrorMessage());
		}
		return null;
	}
	
	/* (non-Javadoc)
	 * @see com.xiaoka.ins.corp.api.gpic.service.GpicService#doCallBack(java.lang.String)
	 */
	@Override
	public String doCallBack(String responseXml){
		try {
			RootElementGPIC rootElementGPIC = jaxbUtils.xmlToBean(responseXml);
			Integer requestType = rootElementGPIC.get_package().getHeader().getRequestType();
			if(215==requestType){
				gpicInterface.doCallBack215(rootElementGPIC);
			}else if(230==requestType){
				gpicInterface.doCallBack230(rootElementGPIC);
			}else{
				log.error("回调失败，没有回调接口");
			}
		} catch (JAXBException e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
		return responseXml;
	}
	
}
